package com.ityy.ruiji.service.impl;

import com.ityy.ruiji.common.R;
import com.ityy.ruiji.dao.ShoppingCartDao;
import com.ityy.ruiji.entity.ShoppingCart;
import com.ityy.ruiji.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartDao shoppingCartDao;

    @Override
    public R add(ShoppingCart shoppingCart) {
        ShoppingCart shoppingCartList = shoppingCartDao.findBy(shoppingCart);

            if (shoppingCartList == null) {
                shoppingCart.setNumber(1);
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCartDao.add(shoppingCart);
                return R.success(shoppingCart);
            } else {
                shoppingCartList.setNumber(shoppingCartList.getNumber() + 1);
                shoppingCartDao.update(shoppingCartList);
                return R.success(shoppingCartList);
            }
    }

    @Override
    public R listCartItemByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartDao.findByUserId(userId);
        return R.success(shoppingCartList);
    }

    /**
     * 根据用户的id清空购物车
     * @param userId
     */
    @Override
    public R cleanShoppingCart(Long userId) {
        shoppingCartDao.cleanShoppingCart(userId);
        return R.success("清空成功");
    }
}
